package cn.topcodes.tcsf.app.web.controller.help;

import cn.topcode.unicorn.utils.StringUtil;
import cn.topcodes.tcsf.app.domain.entity.HelpArticle;
import cn.topcodes.tcsf.app.domain.entity.HelpArticleCatalog;
import cn.topcodes.tcsf.app.service.HelpArticleCatalogService;
import cn.topcodes.tcsf.app.service.HelpArticleService;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;

/**
 * 帮助
 * @author Unicorn
 * @date 2018/6/12
 */
@Controller
@RequestMapping("/kf/help")
public class AppHelpController {

    @Autowired
    private HelpArticleCatalogService helpArticleCatalogService;

    @Autowired
    private HelpArticleService helpArticleService;

    @GetMapping("index")
    public String index(
            Long parentCatalogId,
            String keyword,
            Model model
    ) {
        String title = null;
        List<HelpArticleCatalog> catalogs = null;
        if(StringUtil.isBlank(keyword)) {
            catalogs = helpArticleCatalogService.findByParent(parentCatalogId);
            if(parentCatalogId != null) {
                HelpArticleCatalog catalog = this.helpArticleCatalogService.findOne(parentCatalogId);
                Assert.notNull(catalog, "找不到分类");
                title = catalog.getName();
            }else {
                title = "帮助中心";
            }
        }else {
            catalogs = Lists.newArrayList();
            title = "搜索 " + keyword;
        }
        model.addAttribute("catalogs", catalogs);
        model.addAttribute("title", title);
        model.addAttribute("keyword", keyword);

        List<HelpArticle> articles = helpArticleService.findByCatalog(parentCatalogId, keyword);
        model.addAttribute("articles", articles);


        return "help/index";
    }

    @GetMapping("article")
    public String article(
            @RequestParam(required = true) Long id,
            Model model
    ) {
        HelpArticle article = helpArticleService.findOne(id);
        article.setContent(StringEscapeUtils.unescapeHtml4(article.getContent()));
        model.addAttribute("article", article);
        return "help/article";
    }
}
